﻿using System;
using System.Data;
using System.Globalization;
using System.Web.UI;
using System.Web.UI.WebControls;
using ContractManagementSystem.BusinessLogicLayer;
using ContractManagementSystem.EntityObjects;

namespace ContractManagementSystem.Presentation.TimesheetManagement
{
    public partial class ApproveTimesheet : Page
    {
        private int _roleId;
        private string _userName;

        protected void Page_Load(object sender, EventArgs e)
        {
            CheckUserPermission();
            if(Session["RoleId"]==null && Session["UserName"]==null)
            {
                return;
            }
            if(!IsPostBack)
            {
                BindData();
                BindDataContract();
            }
        }

        protected void Page_PreRender(object sender, EventArgs e)
        {
            FilterClick(null, null);
            approveTimesheet.DataBind();
        }

        private void BindData()
        {
            _roleId = int.Parse(Session["RoleId"].ToString(),CultureInfo.InvariantCulture);
            _userName = Session["UserName"].ToString();
            if(_roleId==3)
            {
                approveTimesheet.DataSource = TimesheetLogic.SelectDataTimesheetByClient(_userName);                
            }
            else if(_roleId==1)
            {
                approveTimesheet.DataSource = TimesheetLogic.SelectDataTimesheet();
            }
            approveTimesheet.DataBind();
        }

        protected void BindDataContract()
        {
            dropContract.DataSource = ContractLogic.ListActiveContracts();
            dropContract.DataTextField = "ContractNumber";
            dropContract.DataValueField = "ContractNumber";
            dropContract.DataBind();
            dropContract.Items.Insert(0,new ListItem("All","All"));
        }

        protected void ApproveTimesheetItemCommand(object sender, CommandEventArgs e)
        {
            if (e.CommandName == "Approve")
            {
                var id = e.CommandArgument.ToString();
                if (!string.IsNullOrEmpty(id))
                {
                    var timesheet = new TimesheetDetailEntity
                                        {
                                            TimesheetDetailId = int.Parse((id),CultureInfo.InvariantCulture),
                                            Status = "Approved",
                                            Reason = ""
                                        };
                    var approve = TimesheetLogic.ApproveTimesheet(timesheet);
                    if (!string.IsNullOrEmpty(approve))
                    {
                        BindData();
                        labelResult.Visible = true;
                        labelResult.Text = approve;
                    }
                    else
                    {
                        const string resultMessage = "Approve Failed";
                        // Save event of logging out
                        var userEventEntity = new EventEntity
                                                  {
                                                      UserName = CommonLogic.ConvertToString(Session["UserName"]),
                                                      OnDate = DateTime.Now,
                                                      EventType = (int) EventTypeList.UserEvent,
                                                      Description = resultMessage
                                                  };

                        EventTracer.SaveEvents(userEventEntity);
                        labelResult.Visible = true;
                        labelResult.Text = approve;
                    }
                }
                upGrid.Update();
            }

            else if (e.CommandName == "Reject")
            {
                var id = e.CommandArgument.ToString();
                
                if (!string.IsNullOrEmpty(id))
                {
                    Session["TimesheetID"] = id;
                    var timesheet = new TimesheetDetailEntity
                                        {
                                            TimesheetDetailId = int.Parse((id),CultureInfo.InvariantCulture),
                                            Status = "Rejected"
                                        };
                    var approve = TimesheetLogic.ApproveTimesheet(timesheet);
                    if (!string.IsNullOrEmpty(approve))
                    {
                        BindData();
                        labelResult.Text = approve;
                    }
                    else
                    {
                        const string resultMessage = "Reject Failed";
                        // Save event of logging out
                        var userEventEntity = new EventEntity
                                                  {
                                                      UserName = CommonLogic.ConvertToString(Session["UserName"]),
                                                      OnDate = DateTime.Now,
                                                      EventType = (int) EventTypeList.UserEvent,
                                                      Description = resultMessage
                                                  };

                        EventTracer.SaveEvents(userEventEntity);
                    }
                }
            }
        }

        protected void AddReasonClick(object sender, EventArgs e)
        {
            textTimesheetId.Text = Session["TimesheetID"].ToString();

            if (Page.IsValid)
            {
                var timesheetId = textTimesheetId.Text;
                if(string.IsNullOrEmpty(textNewReason.Text))
                {
                    return;
                }
                if (!string.IsNullOrEmpty(timesheetId))
                {
                    var timesheet = new TimesheetDetailEntity
                                        {
                                            TimesheetDetailId = int.Parse((timesheetId),CultureInfo.InvariantCulture),
                                            Reason = textNewReason.Text
                                        };
                    var reason = TimesheetLogic.UpdateReason(timesheet);
                    if (reason != null)
                    {
                        BindData();
                    }
                    else
                    {
                        // Save event of logging out
                        var userEventEntity = new EventEntity
                                                  {
                                                      UserName = CommonLogic.ConvertToString(Session["UserName"]),
                                                      OnDate = DateTime.Now,
                                                      EventType = (int) EventTypeList.UserEvent,
                                                      Description = "reason failed"
                                                  };

                        EventTracer.SaveEvents(userEventEntity);
                    }
                }
                CloseDialog("newReason");
                textNewReason.Text = string.Empty;
                //refect listview
                upGrid.Update();
            }
        }

        protected void FilterApproveTimesheet()
        {
            var contractDrop = dropContract.SelectedValue;
            var statusDrop = dropStatus.SelectedValue;

            var timesheetEntity = new TimesheetDetailEntity
                                      {
                                          ContractNumber = contractDrop,
                                          Status = statusDrop
                                      };
            var result = TimesheetLogic.FilterApproveTimesheet(timesheetEntity);
            if (result == null)
            {
                return;
            }

            approveTimesheet.DataSource = result;
            approveTimesheet.DataBind();
        }

        protected void FilterApproveTimesheetByClient()
        {
            _userName = Session["UserName"].ToString();

            if(_userName==null)
            {
                return;
            }

            var contractDrop = dropContract.SelectedValue;
            var statusDrop = dropStatus.SelectedValue;

            var timesheetEntity = new TimesheetDetailEntity
            {
                ContractNumber = contractDrop,
                Status = statusDrop
            };
            var result = TimesheetLogic.FilterApproveTimesheetByClient(_userName, timesheetEntity);
            if (result == null)
            {
                return;
            }

            approveTimesheet.DataSource = result;
            approveTimesheet.DataBind();
        }

        protected void FilterClick(object sender, EventArgs e)
        {
            _roleId = int.Parse(Session["RoleId"].ToString(), CultureInfo.InvariantCulture);

            if(_roleId==1)
            {
                FilterApproveTimesheet();    
            }
            else if(_roleId==3)
            {
                FilterApproveTimesheetByClient();
            }
        }

        protected void LinkEditReason(object sender, EventArgs e)
        {

            var editReason = (LinkButton) sender;
            labelId.Text = editReason.CommandArgument;
            var timesheetId = int.Parse(labelId.Text, CultureInfo.InvariantCulture);
            var result = TimesheetLogic.SelectReasonById(timesheetId);
            if (result == null)
            {
                return;
            }
            textEditReason.Text = result.Rows[0]["Description"].ToString();
            upEditUpdatePanel.Update();

        }

        protected void EditReasonClick(object sender, EventArgs e)
        {
            if (Page.IsValid)
            {
                var timesheet = new TimesheetDetailEntity
                                    {
                                        Reason = textEditReason.Text,
                                        TimesheetDetailId = int.Parse(labelId.Text, CultureInfo.InvariantCulture)
                                    };
                var result = TimesheetLogic.UpdateReason(timesheet);
                if(result=="Successfully!")
                {
                    DataBind();   
                }
                else
                {
                    // Save event of logging out
                    var userEventEntity = new EventEntity
                    {
                        UserName = CommonLogic.ConvertToString(Session["UserName"]),
                        OnDate = DateTime.Now,
                        EventType = (int)EventTypeList.UserEvent,
                        Description = "edit reason failed"
                    };

                    EventTracer.SaveEvents(userEventEntity);
                }
                CloseDialog("editReason");
                textEditReason.Text = string.Empty;
                //refect listview
                upGrid.Update();
            }
        }

        // Check user's permissions
        private void CheckUserPermission()
        {
            var userName = CommonLogic.ConvertToString(Session["UserName"]);
            const int functionId = (int)FunctionList.ApproveTimesheet;

            var urlToCome = Page.Master.ResolveUrl("Presentation/AuthorizationError.aspx");

            AuthorizationChecker.IsValidAuthorization(userName, functionId, Response, urlToCome);
        }
        /// <summary>
        /// Registers client script to close the dialog
        /// </summary>
        /// <param name="dialogId"></param>
        private void CloseDialog(string dialogId)
        {
            string script = string.Format(CultureInfo.InvariantCulture,@"closeDialog('{0}')", dialogId);
            ScriptManager.RegisterClientScriptBlock(this, typeof (Page), UniqueID, script, true);
        }
        //private void ShowDialog(string dialogId)
        //{
        //    string script = string.Format(CultureInfo.InvariantCulture, @"showDialog('{0}')", dialogId);
        //    ScriptManager.RegisterClientScriptBlock(this, typeof(Page), UniqueID, script, true);
        //}
    }
}